var express = require('express');
var router = express.Router();
// 对暴露的表进行导入，在{}写入要导入的需要导入的表名，然后在require中写上module.js的路径
var { doctorModel, List_of_historical_prescriptionModel, bankMdoel } = require('../../module/module')
// 使用multiparty对获取前端上传的图片或者文件
var multiparty = require('multiparty')
// 导入node-xlsx对上传过来的文件中的内容进行读取
var xlsx = require('node-xlsx')
// 使用jsonwebtoken创建生成token
var jwt = require("jsonwebtoken")
const bodyParser = require('body-parser');
const axios = require('axios');
const UniSMS = require('unisms').default
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");



/* GET home page. */
router.get('/getdoctor', async (req, res) => {
  let id = req.query.id
  let list = await doctorModel.find({ _id: id })
  res.send({
    code: 200,
    list
  })
});

router.post('/upname', async (req, res) => {
  let { id, inp } = req.body
  console.log(id, inp);
  await doctorModel.updateOne({ _id: id }, { doctor_name: inp })
  res.send({
    code: 200
  })
});

router.post('/setdoctor_department', async (req, res) => {
  let { id, doctor_department } = req.body
  await doctorModel.updateOne({ _id: id }, { doctor_department })
  res.send({
    code: 200
  })
});

router.post('/updoctor_title', async (req, res) => {
  let { id, doctor_title } = req.body
  await doctorModel.updateOne({ _id: id }, { doctor_title })
  res.send({
    code: 200
  })
});

//擅长领域修改
router.post('/upfield', async (req, res) => {
  let { id, inp } = req.body
  console.log(id, inp);
  await doctorModel.updateOne({ _id: id }, { Areas_of_expertise: inp })
  res.send({
    code: 200
  })
});

//个人经历修改
router.post('/upexperience', async (req, res) => {
  let { id, inp } = req.body
  await doctorModel.updateOne({ _id: id }, { Areas_of_expertise: inp })
  res.send({
    code: 200
  })
})

//获取病历单查看并单
router.post('/getprescription', async (req, res) => {
  let { id } = req.body
  console.log(id);
  let list = await List_of_historical_prescriptionModel.find({ doctor_id: id })
  res.send({
    code: 200,
    list
  })
})

//修改接诊状态
router.post('/upcheck', async (req, res) => {
  let { id, check } = req.body
  await doctorModel.updateOne({ _id: id }, { Professional_Experience: !check })
  res.send({
    code: 200,
  })
})

//修改接诊价格
router.post('/upprice', async (req, res) => {
  let { id, visible } = req.body
  visible = Number(visible)
  await doctorModel.updateOne({ _id: id }, { price: visible })
  res.send({
    code: 200,
  })
})

//修改密码
router.post('/uppsd', async (req, res) => {
  let { id, psd } = req.body
  await doctorModel.updateOne({ _id: id }, { password: psd })
  res.send({
    code: 200,
  })
})



//发送验证码
router.get('/getyzm', async (req, res) => {
  const client = new UniSMS({
    accessKeyId: 'PYqSuZEnwZjnsxvoXFhYRWsi59ZARzufsKDk8U4D7mvGret3X',
    accessKeySecret: 'NRz14j3Yz7v6xX8djJoJNoW6N9nLDN', //当你实名认证之后就会自动生成ID，直接复制就行
  })
  const phone = req.query.phone
  //生成随机的四位数验证码，也可以修改成其他几位数验证码
  const len = Math.floor(1000 + Math.random() * 9000)
  //  发送短信
  client.send({
    to: phone,
    signature: '董起嘉',
    templateId: 'pub_verif_basic', //短信报备中模板管理，在里面随便复制一个通道就可以
    templateData: {
      code: len,
    },
  }).then(ret => {
    res.send({
      code: ret.code,
      len: len
    })
  }).catch(err => {
    console.log(err);
  })
})

router.post('/upphone', async (req, res) => {
  let { id, phone } = req.body
  await doctorModel.updateOne({ _id: id }, { phone: phone })
  res.send({
    code: 200
  })
})


//图片上传
router.post('/upload', async (req, res) => {
  //配置mulitpart模块
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, (err, files, info) => {
    let path = "http://localhost:3000/" + info.file[0].path
    //返回上传图片路径
    // console.log(path);
    res.send({
      code: 200,
      path: path
    })

  })
});



// 人脸识别
router.post('/faceLogin', async (req, res) => {
  //获取前端传来的base64
  let b64 = req.body.body
  // console.log(b64);
  const IaiClient = tencentcloud.iai.v20200303.Client;
  const clientConfig = {
    credential: {
      //自己的腾讯secretId
      secretId: "AKIDTogqsgGcuLhsvrgMtGiCtTp10lIbzFRZ",
      //自己的腾讯密匙
      secretKey: "zlPr66ykv56tVt3yfASWMyNYVBg6MQd4",
    },
    region: "ap-beijing",  //地域参数（华北地区北京）
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };
  const client = new IaiClient(clientConfig);
  const params = {
    "GroupIds": [  //你创建的人员库ID
      "123123"
    ],
    "Image": b64,  //图片的base64格式编码
    "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
    "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
    "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
  };
  let doc = await client.SearchFaces(params)
  //doc为人脸识别后的返回信息
  // console.log(doc, 'doc');
  if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
    let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
    // console.log(personName, 'personNume');
    let user = await doctorModel.find({ doctor_name: personName })
    console.log(personName, 'personName');
    console.log(user[0], 'user');

    if (user != '') {
      if (user[0].authentication == true) {
        user[0].authentication = false   //对数据库中该人员的工作状态进行修改和验证
        await doctorModel.updateOne({ doctor_name: personName }, user[0])
        res.send({
          code: 200,
        })
      } else {
        res.send({
          code: 200,
          msg: '该人员已经是工作状态，无需重复认证'
        })
      }
    } else {
      res.send({
        code: 404,
        msg: '该人员不存在'
      })
    }
  }
})



router.post('/upauthentication', async (req, res) => {
  let { id, authentication } = req.body
  console.log(id, authentication);
  await doctorModel.updateOne({ _id: id }, { authentication: authentication })
  res.send({
    code: 200
  })
})




module.exports = router;
